﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using EZCRS.HCMS.Entity;
using EZCRS.HCMS.Bll;
using EZCRS.HCMS.Web;
using System.IO;
using EZCRS.HCMS.Bll.baseinfo;

namespace EZCRS.HCMS.Web.manage.hotel
{
    public partial class imgact : ManageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
            Response.Cache.SetNoStore();

            if (base.BasHotelId == 0)
                Response.Write(CFun.AlertMeg(Resources.Site.MustHotel, "back", ""));
            else
            {
                if (!IsPostBack)
                {

                    CheckModule(58);

                    List<dropdowndata> _list = Bllbase_info.getbaseinfo(baseinfotype.酒店图片类型, base.LanguageId);
                    CFun.SetListControl(ddlPhotoType, _list, "");
                    //Request
                    if (Request.Params["photoname"] != null)
                    {
                        if (Request.Params["phototype"] != null)
                        {
                            int iType = 0;
                            int.TryParse(Request.Params["phototype"], out iType);

                            int iPhotoID = 0;

                            if (Request.Params["photoid"] != null)
                                int.TryParse(Request.Params["photoid"], out iPhotoID);

                            string strPhotoName = Request.Params["photoname"];

                            string strFile = string.Empty;

                            if (Request.Files.Count > 0)
                            {
                                //upload file

                                HttpPostedFile file = Request.Files[0];

                                if (iPhotoID == 0)
                                    SaveFile(file, strPhotoName, iType, out strFile, out iPhotoID);
                                else
                                {
                                    //update photo...
                                    UpdatePhoto(iPhotoID, file, strPhotoName, iType, out strFile);
                                }

                                //create json data
                                string strJSON = "{photoname: \"" + HttpUtility.HtmlEncode(strPhotoName) + "\", type: " +
                                    iType.ToString() + ", photoid:" + iPhotoID.ToString() + ", url:\"" + strFile.Replace("\\", "\\\\") + "\"}";

                                Response.Write(strJSON);
                                Response.End();
                            }
                            else
                            {
                                //update photo without file

                                UpdatePhoto(iPhotoID, strPhotoName, iType, out strFile);

                                //create json data
                                string strJSON = "{photoname: \"" + HttpUtility.HtmlEncode(strPhotoName) + "\", type: " +
                                    iType.ToString() + ", photoid:" + iPhotoID.ToString() + ", url:\"" + strFile.Replace("\\", "\\\\") + "\"}"; ;

                                Response.Write(strJSON);
                                Response.End();
                            }
                        }
                    }
                    else
                    {

                        if (Request.QueryString["id"] != null)
                        {
                            int iPhotoID = 0;

                            if (!int.TryParse(Request.QueryString["id"].Replace("photo", string.Empty), out iPhotoID))
                                int.TryParse(Request.QueryString["id"].Replace("del", string.Empty), out iPhotoID);

                            if (Request.QueryString["action"] != null)
                            {
                                if (Request.QueryString["action"].ToLower() == "get")
                                {
                                    //get photo by id
                                    RequestPhotoInfo(iPhotoID);
                                }
                                else if (Request.QueryString["action"].ToLower() == "del")
                                {
                                    //delete photo by id
                                    DeletePhotoRequest(iPhotoID);
                                }
                            }
                        }
                        else
                        {
                            //show page
                            BindPhoto();
                        }
                    }
                }
            }
        }


        /// <summary>
        /// 获取照片信息输出JSON
        /// </summary>
        /// <param name="PhotoID"></param>
        private void RequestPhotoInfo(int PhotoID)
        {
            BllHotelUtil hotel = new BllHotelUtil();

            DataTable dtPhoto = hotel.GetHotelPhotoByID(PhotoID);

            if (dtPhoto.Rows.Count > 0)
            {

                string strFile = dtPhoto.Rows[0]["photourl"].ToString();

                int iType = 0;
                int.TryParse(dtPhoto.Rows[0]["phototype"].ToString(), out iType);

                string strPhotoName = dtPhoto.Rows[0]["photoname"].ToString();

                string strJSON = "{photoname: \"" + HttpUtility.HtmlEncode(strPhotoName) + "\", type: " +
                        iType.ToString() + ", photoid:" + PhotoID.ToString() + ", url:\"" + strFile.Replace("\\", "\\\\") + "\"}";


                Response.Write(strJSON);
                Response.End();
            }

        }

        /// <summary>
        /// 删除照片
        /// </summary>
        /// <param name="PhotoID"></param>
        private void DeletePhotoRequest(int PhotoID)
        {

            BllHotelUtil hotel = new BllHotelUtil();

            bool b = hotel.DeletePhoto(PhotoID);

            if (b)
            {
                string strJSON = "{ photoid:" + PhotoID.ToString() + "}";

                Response.Write(strJSON);
                Response.End();
            }


        }

        /// <summary>
        /// 绑定图片
        /// </summary>
        private void BindPhoto()
        {
            BllHotelUtil hotel = new BllHotelUtil();

            DataTable dt = hotel.GetHotelPhoto(base.BasHotelId);
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            foreach (ListItem _item in ddlPhotoType.Items)
            {
                sb.Append("<table align=\"center\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"maininfo\">\r\n");
                sb.Append("                <tr>\r\n");
                sb.Append("                    <th class=\"minfo-title\">\r\n");
                sb.Append("                        " + _item.Text + "\r\n");
                sb.Append("                    </th>\r\n");
                sb.Append("                </tr>\r\n");
                sb.Append("                <tr>\r\n");
                sb.Append("                    <td class=\"cxledit\">\r\n");

                if (_item.Value != "1")
                    sb.Append("<ul class='photologo'>");
                else
                    sb.Append("<ul class='photoul'>");

                foreach (DataRow dr in dt.Rows)
                {
                    string iType = dr["phototype"].ToString();

                    if (iType == _item.Value)
                        sb.Append(string.Format("<li id=\"l{2}\"><a id=\"photo{2}\" href=\"#\" class=\"getthis\"><img src='{0}' class='imgphoto'/></a><br/><span id='sp{2}'>{1}</span><br/>" +
                                                 "<a id=\"del{2}\" href=\"#\" class='delphoto'><img src=\"..\\..\\image\\delete.gif\" /></a></li>",
                                                 dr["photourl"].ToString().Replace('\\','/'), HttpUtility.HtmlEncode(dr["photoname"].ToString()), dr["photoid"]) + "\r\n");
                }
                sb.Append("</ul>");
                sb.Append("                    </td>\r\n");
                sb.Append("                </tr>\r\n");
                sb.Append("            </table>\r\n");
            }

            ltllist.Text = sb.ToString();
        }


        /// <summary>
        /// 新上传
        /// </summary>
        /// <param name="file"></param>
        /// <param name="PhotoName"></param>
        /// <param name="PhotoType"></param>
        /// <param name="FileName"></param>
        /// <param name="PhotoID"></param>
        /// <returns></returns>
        private bool SaveFile(HttpPostedFile file, string PhotoName, int PhotoType, out string FileName, out int PhotoID)
        {

            string strFileName = DateTime.Now.Ticks.ToString();
            string strPath = string.Empty;
            string strExtension = Path.GetExtension(file.FileName).ToLower();

            string strFolder = "\\" + System.Configuration.ConfigurationManager.AppSettings["uploadphotopath"] +
                "\\" + base.BasHotelId.ToString() + "\\";

            strPath = Server.MapPath(strFolder);

            if (!Directory.Exists(strPath))
                Directory.CreateDirectory(strPath);

            FileName = strFolder + strFileName + strExtension;

            strFileName = strPath + strFileName + strExtension;

            try
            {
                file.SaveAs(strFileName);
            }
            catch (HttpException ex)
            {
                PhotoID = 0;
                return false;
            }

            BllHotelUtil hotel = new BllHotelUtil();

            return hotel.AddPhoto(base.BasHotelId, PhotoName, FileName, PhotoType, out PhotoID);

        }


        /// <summary>
        /// 更新照片信息
        /// </summary>
        /// <param name="PhotoID"></param>
        /// <param name="file"></param>
        /// <param name="PhotoName"></param>
        /// <param name="PhotoType"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        private bool UpdatePhoto(int PhotoID, HttpPostedFile file, string PhotoName, int PhotoType, out string FileName)
        {

            string strFileName = DateTime.Now.Ticks.ToString();
            string strPath = string.Empty;
            string strExtension = Path.GetExtension(file.FileName).ToLower();

            string strFolder = "\\" + System.Configuration.ConfigurationManager.AppSettings["uploadphotopath"] +
                "\\" + base.BasHotelId.ToString() + "\\";

            strPath = Server.MapPath(strFolder);

            if (!Directory.Exists(strPath))
                Directory.CreateDirectory(strPath);

            FileName = strFolder + strFileName + strExtension;

            strFileName = strPath + strFileName + strExtension;

            try
            {
                file.SaveAs(strFileName);
            }
            catch (HttpException ex)
            {
                PhotoID = 0;
                return false;
            }

            BllHotelUtil hotel = new BllHotelUtil();

            return hotel.UpdatePhoto(PhotoID, PhotoName, FileName, PhotoType);

        }


        /// <summary>
        /// 更新照片信息
        /// </summary>
        /// <param name="PhotoID">照片ID</param>
        /// <param name="PhotoName">照片名称</param>
        /// <param name="PhotoType">照片类型</param>
        /// <param name="FileName">文件名</param>
        /// <returns></returns>
        private bool UpdatePhoto(int PhotoID, string PhotoName, int PhotoType, out string FileName)
        {
            BllHotelUtil hotel = new BllHotelUtil();

            DataTable dt = hotel.GetHotelPhotoByID(PhotoID);

            FileName = string.Empty;

            if (dt.Rows.Count > 0)
            {
                FileName = dt.Rows[0]["photourl"].ToString();
            }

            return hotel.UpdatePhoto(PhotoID, PhotoName, PhotoType);

        }

    }
}
